/**
 * @file: 
 * @author: Lengxx
 * @date: 2024-06-19
 */
<template>
  <PanelTitle title="修改密码" />
  <Form 
  class="w-1/2 mt-10"
  :label-col="{ span: 8 }"
  :wrapper-col="{ span: 16 }"
  autocomplete="off"
  >
    <FormItem label="旧密码" name="password" v-bind="validateInfos.password"  >
      <Input type="password" v-model:value="formState.password" placeholder="请输入旧密码" allowClear />
    </FormItem>
    <FormItem label="新密码" name="newPassword" v-bind="validateInfos.newPassword" >
      <Input type="password" v-model:value="formState.newPassword" placeholder="请输入新密码" allowClear />
    </FormItem>
    <FormItem label="确认新密码" name="reNewPassword" v-bind="validateInfos.reNewPassword" >
      <Input type="password" v-model:value="formState.reNewPassword" placeholder="请再次输入新密码" allowClear />
    </FormItem>
    <FormItem :wrapper-col="{ offset: 8, span: 16 }">
      <Button type="primary" @click="onSubmit" :loading="loading">提 交</Button>
    </FormItem>
  </Form>
</template>

<script lang="ts" setup>
import { reactive } from 'vue'
import { useRequest } from '@vben/hooks'
import { useMessage } from '@/hooks/web/useMessage'
import { PanelTitle } from '@/components/PanelTitle'
import { Form, FormItem, Input, Button } from 'ant-design-vue'
import { IUpdatePassword, updatePassword } from '@/api/user';
import { Rule } from '@/components/Form/index';
import { useUserStore } from '@/store/modules/user'

const userStore = useUserStore();
const { createMessage } = useMessage();
const { loading, runAsync: updatePwdFnc } = useRequest(updatePassword, { manual: true })

const rules = reactive({
  password: [{ required: true, message: '该字段不能为空!' }],
  newPassword: [
    { required: true, message: '该字段不能为空!' },
    { required: true, validator: newPwdValidator }
  ],
  reNewPassword: [
    { required: true, message: '该字段不能为空!' },
    { required: true, validator: reNewPwdValidator }
  ],
})

const useForm = Form.useForm;

const formState = reactive({
  password: '',
  newPassword: '',
  reNewPassword: ''
})

const { validate, validateInfos  } = useForm(formState, rules);

function newPwdValidator(_rule: Rule, value: string) {
  if (value === formState.password) {
    return Promise.reject('与旧密码不能相同!')
  }
  return Promise.resolve()
}

function reNewPwdValidator(_rule: Rule, value: string) {
  if (value !== formState.newPassword) {
    return Promise.reject('两次密码不一致!')
  }
  return Promise.resolve()
}

async function onSubmit() {
  const { password, newPassword, reNewPassword } = await validate<IUpdatePassword>();
  const data: IUpdatePassword = {
    password: password,
    newPassword: newPassword,
    reNewPassword: reNewPassword
  }
  await updatePwdFnc(data);
  createMessage.success('修改密码成功!');
  userStore.confirmLoginOut();
}

</script>